package org.lex.splitter.ui.awt.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.lex.splitter.core.Splitter;
import org.lex.splitter.util.StringUtils;

public class RunButtonAction extends BaseActionListener {
	private Splitter split = new Splitter();

	public void actionPerformed(ActionEvent e) {
		File input = this.getContentPane().getInputFile();
		File output = this.getContentPane().getOutputFolder();
		int size = this.getContentPane().getSplitSize();
		try {
			List<File> results = split.split(input, output, size);
			this.showResults(results);
		} catch (Exception ioe) {
			log.error("Split failed", ioe);
			this.showError(ioe);
		}
	}

	private void showResults(List<File> results) {
		StringBuilder buf = new StringBuilder();
		buf.append(results.size());
		buf.append(" files wrote in folder " + this.getContentPane().getOutputFolder());
		String prompt = buf.toString();

		buf.setLength(0);
		for (Iterator<File> iter = results.iterator(); iter.hasNext();) {
			buf.append(iter.next());
			buf.append(StringUtils.nl);
		}
		String message = buf.toString();

		showMessageDialog("Success", prompt, message);
	}

	private void showError(Exception e) {
		showMessageDialog("Failed", "Error happend", StringUtils.toString(e));
	}
}
